﻿using HrEFCore;
using HrService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace HrUI.Controllers
{
	public class CMController : Controller
	{
		private readonly MyDbContext myDbContext;
		private readonly CMService cMService;
		private readonly CMKService cMKService;

		public CMController(MyDbContext myDbContext,CMService cMService,CMKService cMKService)
        {
			this.myDbContext = myDbContext;
			this.cMService = cMService;
			this.cMKService = cMKService;
		}
        public async Task<IActionResult> Index()
		{
			List<CM> list = await cMService.CMSelectAsync();
			ViewData.Model = list;
			return View();
		}
		[HttpGet]
		public async Task<IActionResult> Add()
		{
			//List<CMK> list = await cMKService.InquireAll();
			//ViewData.Model = list;
			List<CMK> list2 = await cMKService.InquireAll();
			SelectList selectListItems = new SelectList(list2,"MajorKindId","MajorKindName");
			ViewBag.cmk = selectListItems;
			return View();
		}
		[HttpPost]
		public async Task<IActionResult> Add(CM cm) 
		{
			CMK cmk = await cMKService.SelectById(cm.MajorKindId);
			cm.MajorKindName = cmk.MajorKindName;
			int row = await cMService.CMAddAsync(cm);
			if (ModelState.IsValid)
			{
				if (row > 0)
				{
					return RedirectToAction("Index");
				}
				else
				{
					return RedirectToAction("Index");
				}
			}
			else
			{
				return RedirectToAction("Index");
			}
		}
		public async Task<IActionResult> Delete(short id) 
		{
			int row = await cMService.CMDeleteAsync(id);
			if(row > 0)
			{
				return RedirectToAction("Index");
			}
			else
			{
				return RedirectToAction("Index");
			}
		}
		
	}
}
